const express = require('express');

const router = express.Router();
//导入数据库操作模块
const db = require('../db/index');

//创建
router.post('/create', (req, res) => {
    //获取数据
    const {
        goods,
        goods_id,
        user_id,
        create_time
    } = req.body;
    
    if (!goods ||!goods_id ||!user_id) {
        res.json({
            code: 400,
            message: '参数不全',
        })
    } else {
        //先查询是否存在
        const selectSql = `select * from collect where goods_id = ${goods_id} and user_id = ${user_id}`;
        db.query(selectSql, (err, result) => {
            if (err) {
                res.json({
                    code: 500,
                    message: '查询失败',
                })
            } else {
                if (result.length > 0) {
                    //存在
                    res.json({
                        code: 300,
                        message: '收藏夹已存在该商品',
                    })
                }else{
                    const sql =`insert into collect(goods,goods_id,user_id,create_time) values(?,?,?,?);`
                    //插入数据
                    db.query(sql, [goods, goods_id, user_id, create_time], (err, result) => {
                        if (err) {
                            res.json({
                                code: 500,
                                message: '服务器错误',
                            })
                        } else {
                            res.json({
                                code: 200,
                                message: '添加成功',
                            })
                        }
                    })
                }
            }
        })
    }
})

//删除
router.post('/delete', (req, res) => {
    let { id } = req.body;
    console.log(id);
    let sql = `delete from collect where id = ${id}`;
    db.query(sql, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                message: '服务器错误',
                data: err
            })
        } else {
            res.json({
                code: 200,
                message: '删除成功',
                data: result
            })
        }
    })
})

//获取用户收藏夹
router.get('/list', (req, res) => {
    let sql = `select * from collect where user_id = ${req.query.user_id}`
    db.query(sql, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                message: '服务器错误',
                data: err
                })
        } else {
            res.json({
                code: 200,
                message: '获取成功',
                books: result
            })
        }
    })
})

module.exports = router;